<template>
	<view class="container">
		<u-navbar :is-back="true" :title="playlistInfo.subject_name || '歌单详情'" :border-bottom="false"
			:custom-back="true" @back="goBack"
			:background="{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }" title-color="#ffffff" />

		<!-- 歌单信息头部 -->
		<view class="playlist-header">
			<image :src="playlistInfo.cover_url || '/static/playlist/default.jpg'" class="playlist-cover-large"
				mode="aspectFill" />
			<view class="playlist-info">
				<view class="playlist-title">{{ playlistInfo.subject_name || '歌单名称' }}</view>
				<view class="playlist-desc">{{ playlistInfo.description || '精选歌单' }}</view>
				<view class="playlist-stats">
					<view class="stats-item">
						<u-icon name="list" size="20" color="#888888"></u-icon>
						<text class="stats-text">{{ songList.length }} 首歌曲</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 操作按钮 -->
		<view class="action-buttons">
			<view class="action-btn primary" @click="playAll">
				<u-icon name="play-circle-fill" size="32" color="#ffffff"></u-icon>
				<text class="action-text">播放全部</text>
			</view>
			<view class="action-btn secondary" @click="addAllToQueue">
				<u-icon name="plus-circle" size="32" color="#667eea"></u-icon>
				<text class="action-text">添加全部</text>
			</view>
		</view>

		<!-- 歌曲列表 -->
		<view class="song-list-container">
			<!-- 下拉刷新 -->
			<scroll-view scroll-y class="song-scroll" :refresher-enabled="true" :refresher-triggered="isRefreshing"
				@refresherrefresh="onRefresh" @scrolltolower="loadMore" :lower-threshold="100">
				<!-- 加载状态 -->
				<view v-if="isLoading && songList.length === 0" class="loading-container">
					<view class="loading-spinner"></view>
					<text class="loading-text">正在加载歌曲...</text>
				</view>

				<!-- 歌曲列表 -->
				<view v-else-if="songList.length > 0" class="song-list">
					<view v-for="(song, index) in songList" :key="song && song.song_id ? song.song_id : `song_${index}`"
						class="song-item">
						<!-- 序号 -->
						<view class="song-index">
							<text class="index-number">{{ index + 1 }}</text>
						</view>

						<!-- 歌曲封面 -->
						<!-- <image :src="song.cover_url || song.cover || '/static/song/default-cover.jpg'"
							class="song-cover" mode="aspectFill" /> -->

						<!-- 歌曲信息 -->
						<view class="song-info">
							<view class="song-title">{{ song.song_name || song.title }}</view>
							<view class="song-artist">{{ song.singer_name || song.artist }}</view>
						</view>

						<!-- 操作按钮 -->
						<view class="song-actions">
							<view class="action-btn-small" @click="song && song.song_id ? orderSong(song) : null">
								<u-icon name="plus-circle" size="36" color="#4ecdc4"></u-icon>
							</view>
							<view class="action-btn-small" @click="song && song.song_id ? onSongMore(song) : null">
								<u-icon name="more-dot-fill" size="36" color="#999999"></u-icon>
							</view>
						</view>
					</view>
				</view>

				<!-- 空状态 -->
				<view v-else class="empty-state">
					<view class="empty-icon">🎵</view>
					<view class="empty-title">暂无歌曲</view>
					<view class="empty-desc">该歌单暂时没有歌曲</view>
				</view>

				<!-- 加载更多 -->
				<view v-if="isLoadingMore" class="loading-more">
					<view class="loading-spinner-small"></view>
					<text class="loading-more-text">加载更多...</text>
				</view>

				<!-- 没有更多 -->
				<view v-if="!hasMore && songList.length > 0" class="no-more">
					<text class="no-more-text">没有更多歌曲了</text>
				</view>
			</scroll-view>
		</view>

		<!-- 歌曲操作弹窗 -->
		<u-popup v-model="showSongActionPopup" mode="bottom" border-radius="20" :mask-close-able="true">
			<view class="song-action-popup">
				<view class="popup-title">歌曲操作</view>
				<view class="action-list">
					<view class="action-item-popup" @click="grabSong">
						<u-icon name="play-circle" size="32" color="#4ecdc4" />
						<text class="action-text-popup">抢歌</text>
					</view>
					<view class="action-item-popup" @click="pinSong">
						<u-icon name="pushpin" size="32" color="#45b7d1" />
						<text class="action-text-popup">置顶</text>
					</view>
				</view>
				<u-button type="default" class="mt-20" @click="showSongActionPopup = false">取消</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
import request from '@/common/request.js';
import ktvCommand from '@/common/ktv-command-utils.js';

export default {
	data() {
		return {
			orderId: '',
			playlistId: '',
			playlistInfo: {},
			songList: [],
			currentPage: 1,
			isLoading: true,
			isRefreshing: false,
			isLoadingMore: false,
			hasMore: true,
			showSongActionPopup: false,
			currentSong: null,
			// 防抖控制
			lastCommandTime: 0,
			commandCooldown: 1000, // 1秒冷却时间
		}
	},
	onLoad(options) {
		this.orderId = options.order_id || '';
		this.playlistId = options.playlist_id || '';

		if (!this.orderId || !this.playlistId) {
			uni.showModal({
				title: '提示',
				content: '缺少必要参数',
				showCancel: false,
				success: () => {
					uni.navigateBack();
				}
			});
			return;
		}

		// 设置歌单基本信息（如果有传入）
		if (options.playlist_name) {
			this.playlistInfo.subject_name = decodeURIComponent(options.playlist_name);
		}
		if (options.cover_url) {
			this.playlistInfo.cover_url = decodeURIComponent(options.cover_url);
		}

		this.loadSongList();
	},
	methods: {
		goBack() {
			uni.navigateBack();
		},

		// 检查是否可以执行命令
		canExecuteCommand() {
			const now = Date.now();
			const timeSinceLastCommand = now - this.lastCommandTime;

			if (timeSinceLastCommand < this.commandCooldown) {
				const remainingTime = Math.ceil((this.commandCooldown - timeSinceLastCommand) / 1000);
				uni.showToast({
					title: `请等待${remainingTime}秒后再操作`,
					icon: 'none',
					duration: 1000
				});
				return false;
			}

			return true;
		},

		// 更新最后命令时间
		updateLastCommandTime() {
			this.lastCommandTime = Date.now();
		},

		// 加载歌曲列表
		async loadSongList(page = 1, isRefresh = false) {
			if (page === 1) {
				this.isLoading = true;
			} else {
				this.isLoadingMore = true;
			}

			try {
				const res = await request.httpTokenRequest({
					url: `/api/ktv/getSubjectSong?order_id=${this.orderId}&page=${page}&subject_id=${this.playlistId}`,
					method: 'get'
				});

				if (res.data.code === 1) {
					let songs = [];
					// 根据接口返回的数据结构解析
					if (res.data.data && res.data.data.data) {
						songs = res.data.data.data;
					} else if (res.data.data && Array.isArray(res.data.data)) {
						songs = res.data.data;
					} else if (res.data.data && res.data.data.list) {
						songs = res.data.data.list;
					}

					// 过滤无效的歌曲数据
					const validSongs = (songs || []).filter(song => {
						const isValid = song &&
							typeof song === 'object' &&
							song.song_id &&
							(song.song_name || song.title);

						if (!isValid) {
							console.warn('发现无效歌曲数据:', song);
						}
						return isValid;
					});

					if (page === 1 || isRefresh) {
						this.songList = validSongs;
					} else {
						this.songList = [...this.songList, ...validSongs];
					}

					// 判断是否还有更多数据
					if (res.data.data && res.data.data.has_more_page !== undefined) {
						this.hasMore = res.data.data.has_more_page;
					} else if (res.data.data && res.data.data.current_page && res.data.data.total) {
						const totalPages = Math.ceil(res.data.data.total / (res.data.data.per_page || 10));
						this.hasMore = res.data.data.current_page < totalPages;
					} else {
						this.hasMore = songs && songs.length >= 10; // 假设每页10条
					}

					this.currentPage = page;
					console.log('获取歌单歌曲成功，当前页:', page, '歌曲数量:', songs?.length || 0);
				} else {
					throw new Error(res.data.msg || '获取歌单歌曲失败');
				}
			} catch (error) {
				console.error('获取歌单歌曲失败:', error);
				uni.showToast({
					title: error.message || '获取歌单歌曲失败',
					icon: 'none'
				});
			} finally {
				this.isLoading = false;
				this.isRefreshing = false;
				this.isLoadingMore = false;
			}
		},

		// 下拉刷新
		onRefresh() {
			this.isRefreshing = true;
			this.currentPage = 1;
			this.hasMore = true;
			this.loadSongList(1, true);
		},

		// 加载更多
		loadMore() {
			if (!this.hasMore || this.isLoadingMore || this.isLoading) return;

			const nextPage = this.currentPage + 1;
			this.loadSongList(nextPage);
		},

		// 播放全部
		async playAll() {
			if (this.songList.length === 0) {
				uni.showToast({
					title: '歌单为空',
					icon: 'none'
				});
				return;
			}

			if (!this.canExecuteCommand()) return;
			this.updateLastCommandTime();

			// 添加第一首歌并播放
			const firstSong = this.songList[0];
			const success = await ktvCommand.addSong(this.orderId, firstSong.song_id);

			if (success) {
				uni.showToast({
					title: '开始播放歌单',
					icon: 'success'
				});
			}
		},

		// 添加全部到播放队列
		async addAllToQueue() {
			if (this.songList.length === 0) {
				uni.showToast({
					title: '歌单为空',
					icon: 'none'
				});
				return;
			}

			if (!this.canExecuteCommand()) return;
			this.updateLastCommandTime();

			uni.showModal({
				title: '确认添加',
				content: `确定要将歌单中的 ${this.songList.length} 首歌曲全部添加到播放队列吗？`,
				success: async (res) => {
					if (res.confirm) {
						uni.showLoading({ title: '正在添加...' });

						let successCount = 0;
						for (let i = 0; i < this.songList.length; i++) {
							const song = this.songList[i];
							const success = await ktvCommand.addSong(this.orderId, song.song_id);
							if (success) {
								successCount++;
							}
							// 添加延迟避免请求过于频繁
							if (i < this.songList.length - 1) {
								await new Promise(resolve => setTimeout(resolve, 200));
							}
						}

						uni.hideLoading();
						uni.showToast({
							title: `成功添加 ${successCount} 首歌曲`,
							icon: 'success'
						});
					}
				}
			});
		},

		// 点歌
		async orderSong(song) {
			// 添加参数验证
			if (!song || typeof song !== 'object') {
				console.error('orderSong: 无效的歌曲参数', song);
				uni.showToast({
					title: '歌曲数据异常',
					icon: 'none'
				});
				return;
			}

			if (!song.song_id) {
				console.error('orderSong: 歌曲ID缺失', song);
				uni.showToast({
					title: '歌曲ID缺失',
					icon: 'none'
				});
				return;
			}

			if (!this.canExecuteCommand()) return;
			this.updateLastCommandTime();

			const success = await ktvCommand.addSong(this.orderId, song.song_id);

			if (success) {
				uni.showToast({
					title: `已点：${song.song_name}`,
					icon: 'success'
				});
			}
		},

		// 显示歌曲操作菜单
		onSongMore(song) {
			this.currentSong = song;
			this.showSongActionPopup = true;
		},

		// 抢歌
		async grabSong() {
			if (!this.currentSong || !this.currentSong.song_id) {
				console.error('grabSong: 无效的歌曲数据', this.currentSong);
				uni.showToast({
					title: '歌曲数据异常',
					icon: 'none'
				});
				this.showSongActionPopup = false;
				return;
			}

			if (!this.canExecuteCommand()) return;
			this.updateLastCommandTime();

			const success = await ktvCommand.insertSong(this.orderId, this.currentSong.song_id);

			if (success) {
				uni.showToast({
					title: `已抢歌：${this.currentSong.song_name}`,
					icon: 'success'
				});
			}
			this.showSongActionPopup = false;
		},

		// 置顶歌曲
		async pinSong() {
			if (!this.currentSong || !this.currentSong.song_id) {
				console.error('pinSong: 无效的歌曲数据', this.currentSong);
				uni.showToast({
					title: '歌曲数据异常',
					icon: 'none'
				});
				this.showSongActionPopup = false;
				return;
			}

			if (!this.canExecuteCommand()) return;
			this.updateLastCommandTime();

			const success = await ktvCommand.insertSong(this.orderId, this.currentSong.song_id);

			if (success) {
				uni.showToast({
					title: `已置顶：${this.currentSong.song_name}`,
					icon: 'success'
				});
			}
			this.showSongActionPopup = false;
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	background: linear-gradient(180deg, #0d0d11 0%, #1a1a1f 100%);
	color: #ffffff;
	min-height: 100vh;
}

.playlist-header {
	display: flex;
	padding: 30rpx;
	gap: 30rpx;
	background: rgba(255, 255, 255, 0.05);
	backdrop-filter: blur(10rpx);
	border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
}

.playlist-cover-large {
	width: 200rpx;
	height: 200rpx;
	border-radius: 20rpx;
	flex-shrink: 0;
}

.playlist-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.playlist-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #ffffff;
	margin-bottom: 15rpx;
	line-height: 1.3;
}

.playlist-desc {
	font-size: 26rpx;
	color: #bfcfff;
	margin-bottom: 20rpx;
}

.playlist-stats {
	display: flex;
	gap: 30rpx;
}

.stats-item {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.stats-text {
	font-size: 24rpx;
	color: #888888;
}

.action-buttons {
	display: flex;
	gap: 20rpx;
	padding: 30rpx;
}

.action-btn {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 10rpx;
	padding: 20rpx;
	border-radius: 15rpx;
	transition: all 0.3s;

	&.primary {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	}

	&.secondary {
		background: rgba(255, 255, 255, 0.1);
		border: 2rpx solid #667eea;
	}

	&:active {
		transform: scale(0.95);
	}
}

.action-text {
	font-size: 28rpx;
	color: #ffffff;
	font-weight: 500;
}

.song-list-container {
	flex: 1;
	height: calc(100vh - 500rpx);
}

.song-scroll {
	height: 100%;
}

.song-list {
	padding: 0 20rpx 40rpx 20rpx;
}

.song-item {
	display: flex;
	align-items: center;
	background: rgba(255, 255, 255, 0.05);
	border-radius: 15rpx;
	padding: 20rpx;
	margin-bottom: 15rpx;
	backdrop-filter: blur(10rpx);
	border: 1rpx solid rgba(255, 255, 255, 0.1);
	transition: all 0.3s;

	&:active {
		transform: scale(0.98);
		background: rgba(255, 255, 255, 0.1);
	}
}

.song-index {
	width: 50rpx;
	height: 50rpx;
	border-radius: 50%;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx;
}

.index-number {
	font-size: 24rpx;
	font-weight: bold;
	color: #ffffff;
}

.song-cover {
	width: 80rpx;
	height: 80rpx;
	border-radius: 12rpx;
	margin-right: 20rpx;
	border: 2rpx solid rgba(255, 255, 255, 0.1);
}

.song-info {
	flex: 1;
	min-width: 0;
}

.song-title {
	font-size: 30rpx;
	font-weight: 500;
	color: #ffffff;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	margin-bottom: 8rpx;
}

.song-artist {
	font-size: 24rpx;
	color: #bfcfff;
}

.song-actions {
	display: flex;
	gap: 15rpx;
}

.action-btn-small {
	padding: 10rpx;
	border-radius: 50%;
	transition: all 0.3s;

	&:active {
		transform: scale(0.9);
		background: rgba(255, 255, 255, 0.1);
	}
}

.loading-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
	gap: 20rpx;
}

.loading-spinner {
	width: 40rpx;
	height: 40rpx;
	border: 4rpx solid #f3f3f3;
	border-top: 4rpx solid #667eea;
	border-radius: 50%;
	animation: spin 1s linear infinite;
}

.loading-text {
	font-size: 28rpx;
	color: #888888;
}

.loading-more {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 15rpx;
	padding: 30rpx;
}

.loading-spinner-small {
	width: 30rpx;
	height: 30rpx;
	border: 3rpx solid #f3f3f3;
	border-top: 3rpx solid #667eea;
	border-radius: 50%;
	animation: spin 1s linear infinite;
}

.loading-more-text {
	font-size: 26rpx;
	color: #888888;
}

.no-more {
	display: flex;
	justify-content: center;
	padding: 30rpx;
}

.no-more-text {
	font-size: 26rpx;
	color: #666666;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 40rpx;
	text-align: center;
}

.empty-icon {
	font-size: 120rpx;
	margin-bottom: 30rpx;
}

.empty-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #ffffff;
	margin-bottom: 15rpx;
}

.empty-desc {
	font-size: 26rpx;
	color: #888888;
}

@keyframes spin {
	0% {
		transform: rotate(0deg);
	}

	100% {
		transform: rotate(360deg);
	}
}

// 歌曲操作弹窗样式
.song-action-popup {
	padding: 40rpx 32rpx 32rpx 32rpx;
	background: #23232b;
	border-radius: 20rpx 20rpx 0 0;
}

.popup-title {
	font-size: 28rpx;
	font-weight: bold;
	margin-bottom: 32rpx;
	color: #ffffff;
	text-align: center;
}

.action-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
	margin-bottom: 30rpx;
}

.action-item-popup {
	display: flex;
	align-items: center;
	gap: 20rpx;
	padding: 20rpx;
	background-color: #1a1a1f;
	border-radius: 15rpx;
	transition: all 0.3s;

	&:active {
		transform: scale(0.98);
		background-color: #2a2a2f;
	}
}

.action-text-popup {
	font-size: 30rpx;
	color: #ffffff;
}

.mt-20 {
	margin-top: 20rpx;
}
</style>
